﻿/*
 * @Description:express启动文件
 * @Author: maskMan
 * @LastEditTime: 2024-01-26 21:14:32
 */
const fs = require("fs");
const https = require("https");
const express = require("express");
const jwt = require("jsonwebtoken");
const regKeyList = ["api", `login\/webLogin`, `login\/wxH5Login`];
const app: any = express();
import { conf } from "./config";
const parser = require("body-parser");
import { assert } from "console";
import { Obj } from "./type";
import { expressjwt } from "express-jwt";
import login from "../api/login";
import admin from "../api/admin";
import user from "../api/user";
import api from "../api/api";
export const AppListen = function () {
  app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Content-Type", "application/json");
    next();
  });
};
//加载中间件监听错误
function _errMiddleWare(err, req, res, next) {
  if (err) {
    if (err.name == "UnauthorizedError") {
      console.error(`用户无token权限`);
      return resSend(res, undefined, "无权限访问数据", false);
    } else {
      assert(false, "中间件加载错误");
    }
  }
}
export const AppMiddleWare = function () {
  try {
    const reglist = [];
    for (let i = 0; i < regKeyList.length; i++) {
      reglist.push(new RegExp("^/" + regKeyList[i] + "/"));
    }
    app.use(parser.urlencoded({ extended: false })); //解析body
    app.use(express.json()); //解析JSON
    app.use(express.urlencoded({ extended: false })); //解析网址字符串
    const ejwt = expressjwt({ secret: conf.secretKey, algorithms: ["HS256"] }).unless({
      path: reglist,
    });
    app.use(ejwt); //解析jwt
    app.use(_errMiddleWare); //加载错误中间件
    app.use(login, admin, user, api);
  } catch (error) {
    assert(false, "中间件错误");
  }
  //session
  // app.use(session({ secret: conf.secret, resave: false, saveUninitialized: true })).unless({ path: [/^\/api\//] }); //session中间件
};
/**token签名
 * @param  data  签名数据
 * @param  string  返回格式
 */
export function jwtSign(data: any): string {
  return jwt.sign(data, conf.secretKey, { expiresIn: conf.tokenExpires });
}
/**http 端口监听
 * @param  port  端口号
 */
export const httpListen = function (): void {
  app.listen(conf.httpPort, function () {
    console.log(`http端口启动成功 ${conf.httpPort}`);
  });
};
/**https 端口监听
 * @param  port  端口号
 */
export const httpsListen = function (): void {
  const key = fs.readFileSync(`${__dirname}/crt/lz.lzmgame.com.key`);
  const cert = fs.readFileSync(`${__dirname}/crt/lz.lzmgame.com.crt`);
  https.createServer({ key: key, cert: cert }, app).listen(conf.httpPort, function () {
    console.log(`https端口启动成功 ${conf.httpPort}`);
  });
};
/**监听静态目录
 */
export const createStaticWeb = function (): void {
  app.use("./admin", express.static("../www/admin/"));
  app.use("./game", express.static("../www/game/"));
  app.use("./web", express.static("../www/web/"));
};
/**
 * @description: 发送返回数据
 * @param {Obj} res 返回路由
 * @param {Object} data 数据
 * @param {string} msg 信息提示
 * @param {boolean} status 状态
 * @param {number} code状态码
 * @return {*}
 */
export const resSend = function (res: Obj, data: Object = null, msg?: string, status?: boolean, code?: number): void {
  try {
    if (status == undefined) {
      status = true;
    }
    if (code == undefined) {
      status == false ? (code = 5000) : (code = 2000);
    }
    if (msg == undefined) {
      status == false ? (msg = "错误") : (msg = "成功");
    }
    let str = JSON.stringify({ status: { suc: status, code, msg }, data });
    res.send(str);
  } catch (error) {
    console.log(error);
  }
};
